import { LockOutlined, MailOutlined } from '@ant-design/icons';
import { Tabs, Form, Alert } from 'antd';
import React, { useState, useRef } from 'react';
import ProForm, {
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
  ProFormInstance,
} from '@ant-design/pro-form';
import { Link, history } from 'umi';
import Footer from '@/components/Footer';
//接口
import { services } from '@/network/api';
import useSubmit from '@/PublicHooks/useSubmit';

import styles from './index.less';
import utils from '@/utils/index';
import logo from '@/asset/img/logo.png';

let email = utils.crypto.deCrypt(localStorage.getItem('email'));
let password = utils.crypto.deCrypt(localStorage.getItem('password'));

const Login: React.FC = () => {
  const [type, setType] = useState<string>('login');
  const [registerData, setRegisterData] = useState<any>({});
  const [registerInfoState, setRegisterInfoState] = useState<boolean>(false);

  const formRef = useRef<ProFormInstance>();
  const _formRef = useRef<ProFormInstance>();

  const handleSubmitLogin = useSubmit(services.login, async (res: any) => {
    await localStorage.setItem('token', res.data['token']);
    if (formRef.current?.getFieldValue('autoLogin')) {
      localStorage.setItem('email', utils.crypto.enCrypt(formRef.current?.getFieldValue('email')));
      localStorage.setItem(
        'password',
        utils.crypto.enCrypt(formRef.current?.getFieldValue('password')),
      );
    }

    // await fetchUserInfo();
    /** 此方法会跳转到 redirect 参数所在的位置 */
    if (!history) return;
    const { query } = history.location;
    const { redirect } = query as { redirect: string };
    setTimeout(() => {
      // location.replace('/crm/');
      location.replace('/crm'+(redirect || '/'));
      // history.replace((redirect || '/'))
      // history.replace((redirect || '/') + 'reloadPage');
    }, 250);
    return;
  });

  const handleSubmitRegister = useSubmit(services.register, async (res: any) => {
    localStorage.setItem('token', res.data['token']);
    setType('login');
    formRef.current?.setFieldsValue(registerData);
    setRegisterInfoState(true)
    return;
  });
  return (
    <div className={styles.container}>
      <div className={styles.lang} data-lang></div>
      <div className={styles.content}>
        <div className={styles.top}>
          <div className={styles.header}>
            <Link to="/">
              <img alt="logo" className={styles.logo} src={logo} />
              <span className={styles.title}>Crm 销管系统</span>
            </Link>
          </div>
          <div className={styles.desc}>一个基于Antd-pro的 Crm销管系统</div>
        </div>

        <div className={styles.main}>
          {registerInfoState && (
            <Alert
              style={{
                marginBottom: 24,
              }}
              message={'注册成功，正在生成用户信息。请尝试在10秒后登录。'}
              type="success"
              showIcon
            />
          )}
          <Tabs activeKey={type} onChange={setType}>
            <Tabs.TabPane key="login" tab={'邮箱密码登录'} />
            <Tabs.TabPane key="register" tab={'邮箱号注册'} />
          </Tabs>
          {type === 'login' && (
            <ProForm
              formRef={formRef}
              initialValues={{
                autoLogin: true,
              }}
              submitter={{
                searchConfig: {
                  submitText: '登录',
                },
                render: (_, dom) => dom.pop(),
                submitButtonProps: {
                  size: 'large',
                  style: {
                    width: '100%',
                  },
                },
              }}
              onFinish={async (values) => {
                delete values.autoLogin;
                await handleSubmitLogin(values)();
              }}
            >
              <>
                <ProFormText
                  name="email"
                  initialValue={email || '1931740796@qq.com'}
                  fieldProps={{
                    size: 'large',
                    prefix: <MailOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder={'请输入用户邮箱'}
                  rules={[
                    {
                      required: true,
                      message: '请输入用户邮箱！',
                    },
                    { type: 'email' },
                  ]}
                />
                <ProFormText.Password
                  name="password"
                  initialValue={password || '123456'}
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder={'请输入密码'}
                  rules={[
                    {
                      required: true,
                      message: '请输入密码！',
                    },
                    {
                      min: 6,
                      message: '密码最少6位!',
                    },
                  ]}
                />
                <div
                  style={{
                    marginBottom: 24,
                  }}
                >
                  <ProFormCheckbox noStyle name="autoLogin">
                    记住密码
                  </ProFormCheckbox>
                  <a
                    style={{
                      float: 'right',
                    }}
                  >
                    忘记密码
                  </a>
                </div>
              </>
            </ProForm>
          )}
          {/* 注册表单 */}
          {type === 'register' && (
            <ProForm
              formRef={_formRef}
              initialValues={{
                autoLogin: true,
              }}
              submitter={{
                searchConfig: {
                  submitText: '注册',
                },
                render: (_, dom) => dom.pop(),
                submitButtonProps: {
                  size: 'large',
                  style: {
                    width: '100%',
                  },
                },
              }}
              onFinish={async (values) => {
                delete values.confirmPassword;            
                await handleSubmitRegister(values)();
                setRegisterData(values);
              }}
            >
              <>
                <ProFormText
                  name="email"
                  fieldProps={{
                    size: 'large',
                    prefix: <MailOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder={'请输入用户邮箱'}
                  rules={[
                    {
                      required: true,
                      message: '请输入用户邮箱!',
                    },
                    { type: 'email' },
                  ]}
                />
                <ProFormText.Password
                  name="password"
                  dependencies={['confirmPassword']}
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder={'请输入密码'}
                  rules={[
                    {
                      required: true,
                      message: '请输入密码!',
                    },
                    {
                      min: 6,
                      message: '密码最少6位!',
                    },
                  ]}
                />
                <ProFormText.Password
                  dependencies={['password']}
                  name="confirmPassword"
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined className={styles.prefixIcon} />,
                  }}
                  placeholder={'请输入确认密码'}
                  rules={[
                    {
                      required: true,
                      message: '请输入确认密码!',
                    },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue('password') === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error('密码与确认密码不一致'));
                      },
                    }),
                  ]}
                />
                <Form.Item noStyle shouldUpdate>
                  {(form) => {
                    return (
                      <ProFormCaptcha
                        fieldProps={{
                          size: 'large',
                          prefix: <LockOutlined className={styles.prefixIcon} />,
                        }}
                        captchaProps={{
                          size: 'large',
                        }}
                        placeholder={'请输入验证码'}
                        captchaTextRender={(timing, count) => {
                          if (timing) {
                            return `${count} ${'获取验证码'}`;
                          }
                          return '获取验证码';
                        }}
                        name="captcha"
                        rules={[
                          {
                            required: true,
                            message: '请输入验证码！',
                          },
                        ]}
                        phoneName="email"
                        onGetCaptcha={async (email) => {
                          form.validateFields(['email']);
                          let res = await services.getRegisterCaptcha({ email });
                          if (!res?.success) {
                            throw new Error('邮箱已被注册');
                          }
                        }}
                      />
                    );
                  }}
                </Form.Item>
              </>
            </ProForm>
          )}
        </div>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
